﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Clipping.Utils
{
    /// <summary>
    /// 鼠标右键点击Treeview节点时，选中该节点
    /// </summary>
    public class TreeViewMouseRightButtonSelectionBehavior : Behavior<TreeView>
    {
        public TreeViewMouseRightButtonSelectionBehavior()
        {

        }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.PreviewMouseRightButtonDown += new MouseButtonEventHandler(AssociatedObject_PreviewMouseRightButtonDown);
        }

        void AssociatedObject_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            DependencyObject source = e.OriginalSource as DependencyObject;
            if (source != null)
            {
                var tvi = ViewHelper.TryFindParentWPF<TreeViewItem>(source);
                if (tvi != null)
                    tvi.IsSelected = true;
            }


        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.PreviewMouseRightButtonDown -= new MouseButtonEventHandler(AssociatedObject_PreviewMouseRightButtonDown);

        }


    }
}
